/*
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-09-17 00:19:34
 * @LastEditTime: 2025-09-17 00:21:55
 */
// 简单网络状态工具（渲染进程）

export async function isOnline(): Promise<boolean> {
    // 优先走主进程判断（更可靠）
    if (typeof window !== 'undefined' && (window as any).net?.isOnline) {
        return await (window as any).net.isOnline()
    }
    return typeof navigator !== 'undefined' ? navigator.onLine : false
}

export async function checkOnline(timeoutMs = 3000): Promise<boolean> {
    if (!isOnline()) return false
    const controller = new AbortController()
    const timer = setTimeout(() => controller.abort(), timeoutMs)
    try {
        const res = await fetch('https://www.gstatic.com/generate_204', {
            method: 'GET',
            signal: controller.signal,
            cache: 'no-store',
        })
        return res.ok
    } catch {
        return false
    } finally {
        clearTimeout(timer)
    }
}

export function onNetworkChange(cb: (online: boolean) => void) {
    const handler = () => cb(isOnline())
    window.addEventListener('online', handler)
    window.addEventListener('offline', handler)
    // 立即通知一次
    cb(isOnline())
    return () => {
        window.removeEventListener('online', handler)
        window.removeEventListener('offline', handler)
    }
}


